package com.eastart.template.util;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;

/**
 * REST API 返回结果
 *
 * @author wangjiao
 * @since 2020/11/14
 */
@Data
@Accessors(chain = true)
@Builder
@AllArgsConstructor
public class ApiResult<T> implements Serializable {
    /** 响应码: 状态码为200才算请求成功 */
    private int code;

    /** 响应消息 */
    private String msg;

    /** 是否成功 */
    private boolean success;

    /** 响应数据 */
    private T data;

    /** 响应时间 */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date time;

    public ApiResult() {
        this.success = true;
        this.msg = ApiCode.SUCCESS.getMsg();
        this.code = ApiCode.SUCCESS.getCode();
        this.time = new Date(System.currentTimeMillis());
    }

    public ApiResult(int code, String msg, boolean success, T data) {
        this.code = code;
        this.msg = msg;
        this.success = success;
        this.data = data;
        this.time = new Date(System.currentTimeMillis());
    }


    public static ApiResult ok(final ApiCode data) {
        return new ApiResult(ApiCode.SUCCESS.getCode(),ApiCode.SUCCESS.getMsg(),true,data);
    }

    public static ApiResult ok(final Object data) {
        return new ApiResult(ApiCode.SUCCESS.getCode(),ApiCode.SUCCESS.getMsg(),true,data);
    }

    public static ApiResult ok(final String msg) {
        return new ApiResult(ApiCode.SUCCESS.getCode(),ApiCode.SUCCESS.getMsg(),true);
    }
    public static ApiResult ok(final String msg,final Object data ) {
        return new ApiResult(ApiCode.SUCCESS.getCode(),msg,true,data);
    }


    public static ApiResult fail() {
        return new ApiResult(ApiCode.FAIL.getCode(),ApiCode.FAIL.getMsg(),false);
    }

    public static ApiResult fail(final String msg) {
        return new ApiResult(ApiCode.FAIL.getCode(),msg,false);
    }

    public static ApiResult fail(final int code,final String msg) {
        return new ApiResult(code,msg,false);
    }

    public ApiResult(int code, String msg, boolean success) {
        this.code = code;
        this.msg = msg;
        this.success = success;
        this.time = new Date(System.currentTimeMillis());
    }

    public static <T> ApiResult<T> fail(IErrorCode errorCode) {
        return ApiResult.fail(errorCode);
    }
}
